﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DI;
using Core.Dtos;
using Core.Messages;
using StructureMap;
using Core.Queries;
using StructureMap.AutoMocking;
using Microsoft.AspNet.Identity;
using System.Threading.Tasks;
using StructureMap.Pipeline;
using Core.ViewModels;
using Front.Core.Dtos;

namespace Tests.Controllers.Admin
{
    [TestClass]
    public class AccountControllerTest
    {
        private UserManager<UserDto, string> userManager;
        private UserDto user;
        private RegisterViewModel registerModel = new RegisterViewModel() { UserName = "demo3", Password = "appdemo" };

        [TestInitialize()]
        public void Initialize()
        {
            Bootstrapper.Init(new SingletonLifecycle());
            Bootstrapper.Container.Configure(x =>
            {
                x.For<UserManager<UserDto, string>>().Transient();
            });
            userManager = Bootstrapper.Resolve<UserManager<UserDto, string>>();
        }

        [TestCleanup()]
        public void Cleanup()
        {
            DeleteUser();
        }

        void DeleteUser() {
            var deleteTask = userManager.DeleteAsync(user);
            deleteTask.Wait();
        }

        [TestMethod]
        public void Account_Can_Register_Manage()
        {
            //Arrange
            user = new UserDto() { UserName = registerModel.UserName };

            //Act & Assert
            Account_Can_Register(user);
            Account_Can_Manage(user);                       
        }
        
        public void Account_Can_Register(UserDto dto)
        {
            //Arrange
            RegisterViewModel model = registerModel;

            //Act
            Task<IdentityResult> task = userManager.CreateAsync(user, model.Password);
            task.Wait();
            if (task.Result.Succeeded)
            {
                var createIdentityTask = userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                createIdentityTask.Wait();
            }

            //Asert
            Assert.IsTrue(task.Result.Succeeded);
        }
       
        public void Account_Can_Manage(UserDto dto)
        {
            //Arrange
            ManageUserViewModel model = new ManageUserViewModel() { OldPassword = registerModel.Password, NewPassword = "appdemo1" };

            //Act
            var manageTask = userManager.ChangePasswordAsync(dto.Id, model.OldPassword, model.NewPassword);
            manageTask.Wait();

            //Assert       
            Assert.IsTrue(manageTask.Result.Succeeded);                                            
        }
    }
}
